package lv.solcraft.replication.server.rest.restlets;

import java.util.List;

import lv.solcraft.replication.server.bdb.Database;
import lv.solcraft.replication.server.bdb.TxTemplateNoResult;
import lv.solcraft.replication.server.dao.OperSiteDataAccess;
import lv.solcraft.replication.server.model.OperSite;
import lv.solcraft.replication.server.model.OperState;

import org.restlet.Context;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;
import org.springframework.util.Assert;

import com.sleepycat.je.Transaction;

public class MoveOperSitesResource extends Resource {

    private Database database;
    private OperSiteDataAccess operSiteDataAccess;
    private int maxItems = 1000;
    private OperState targetOperState;

    public void setDatabase(Database database) {
        this.database = database;
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        long siteId = Long.parseLong(request.getAttributes().get("site").toString());
        Form query = request.getResourceRef().getQueryAsForm();
        maxItems = Integer.parseInt(query.getFirstValue("maxItems", "1000"));
        Assert.isTrue(maxItems <= 100000, "maxItems should be <= 100,000");
        OperState operState = OperState.valueOf(request.getAttributes().get("state").toString());
        operSiteDataAccess = database.getOperSiteDataAccessFactory().getInstance(siteId, operState);
        targetOperState = OperState.valueOf(request.getAttributes().get("targetState").toString());
        Assert.isTrue(operState != targetOperState, "Can not move to the same oper state!");
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }

    @Override
    public boolean allowPost() {
        return true;
    }

    @Override
    public void handlePost() {
        List<OperSite> operSites = operSiteDataAccess.findFirst(maxItems);
        for (final OperSite operSite : operSites) {
            new TxTemplateNoResult(database) {
                @Override
                protected void executeInTxNoResult(Transaction tx) throws Exception {
                    operSite.setState(targetOperState);
                    operSite.setMessage("Moved from state: " + operSite.getState() + ", original message: " + operSite.getMessage());
                    operSite.persist();
                }
            }.execute();
        }
        getResponse().setEntity(new StringRepresentation(Integer.toString(operSites.size())));
    }
}
